define(function(require, exports){
	var $ = require('jquery');
	var util = require('util');
	var pubjs = require('pubjs');
	var view  = require('@base/view');
	var popwin = require('@base/dialog').base;

	// 创建新条件 模块
	var Select = popwin.extend({
		init: function( config ) {
			config = pubjs.conf( config, {
				'view_model': {
				}
			});

			this.Super('init', arguments);
		},
		afterBuild: function(){
			var self = this;
			var c = self.getConfig();
			self.Super('afterBuild',arguments);
			var el = self.getContainer('body');
			// 指数
			el.append(`
				<div class="" pub-name="grid" pub-mod="sweety/grid/picText.selectTemplate"/>
			`);

			self.buildFromTemplate({
				grid: {
					hasFilterSidebar: true,
					sidebar_config: {
						'height': 200,
						'items': [
							{'name': 'Adx', 'uri':'modules/sideBarBase.radio', 'config': {
								'title': LANG('渠道：'),
								'url': 'ptc/list',
								'param': {
									Type: 1
									,mongoField: ['name', 'AdxId']
								},
								'key': 'AdxId',
								'name': 'name',
								'all': true,
								'value': 0
							}},
							{'name': 'terminal_type', 'uri':'modules/sideBarBase.radio', 'config': {
								'title': LANG('终端：'),
								'data': [
									{id: 0, name: LANG('全部终端')},
									{id: 1, name: LANG('iOS')},
									{id: 2, name: LANG('Android')},
									{id: 100, name: LANG('其它')}
								],
								'value': 0
							}}
						]
					}
				}
			});
		},
		onSidebarFilter: function(ev){
			var self = this
				,param = {};

			util.each(ev.param, function(item, idx){
				var type = idx;
				var id = item.id;
				switch (type) {
					case 'Adx':
						param.AdxId = +id;
						break;
					case 'terminal_type':
						param.terminal_type = +id;
						break;
				}
			});

			self.$.grid.reload(param);
			return false;
		},
		validate: function(data)
		{
			var valid = true;
			var array_regex = /[^0-9\s,]/;
			var number_regex = /[^0-9\s]/;
			if(data && data.length)
			{
				util.each(data, function(item) {
					var regex = ['campaign_id', 'package_id'].indexOf(item.dimId) > -1 ? array_regex : number_regex;
					if(!item.value || item.value.match(regex))
					{
						pubjs.alert(`${item.value} 为空或不合规则，请重新输入`);
						valid = false;
						return false;
					}
				});
			}

			return valid;
		},
		setData: function(data, index)
		{
			var vm = this.vm.$;
			return this;
		},
		getData: function() {
			return this.$.grid.getSelectRowIds();
		},
		onOk: function()
		{
			var value = this.getData();
			if(!value.length)
			{
				return pubjs.alert('请选择模板');
			}

			this.fire('templateSelect', {value: value});
			this.hide();
			return false;
		},
		reset: function() {
			this.vm.reset();
			this.$.grid.setSelectRowIds([]);
			this.$.grid.reload();
			return this;
		}
	});

	exports.selectTemplate = Select;
});